package com.jphotomanager.thread;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import com.jphotomanager.io.ImageImporter;
import com.jphotomanager.io.ImageLibrary;
import com.jphotomanager.io.RawConverter;
import com.openroom.db.DBHelper;
import com.openroom.model.ModelLocator;
import com.openroom.model.Photograph;

public class PreviewGeneratingTask implements Runnable {

    private static final Logger LOGGER = Logger
            .getLogger(PreviewGeneratingTask.class);

    private BufferedImage originalImage;
    private Photograph photograph;

    public PreviewGeneratingTask(BufferedImage originalImage,
            Photograph photograph) {
        super();
        this.originalImage = originalImage;
        this.photograph = photograph;
    }

    public PreviewGeneratingTask(Photograph photograph) {
        super();
        try {
            this.originalImage = ImageIO.read(new File(photograph
                    .getRawFilePath()));
            this.photograph = photograph;
        } catch (IOException e) {
            LOGGER.error("error", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void run() {
        try {
            ImageLibrary.getInstance().ow.lock();
            String parent = new File(photograph.getThumbnailPath()).getParent();
            File rawFile = new File(photograph.getRawFilePath());
            File previewImage = new File(parent,
                    RawConverter.getFilenameForPreviewJPG(rawFile));
            if (isRawFile(rawFile) && !RawConverter.isRawFileSupported()) {
                if (RawConverter.isSupportedRawFile(rawFile)) {
                    File jpegFile = RawConverter.extractJpeg(rawFile);
                    if (jpegFile != null) {
                        rawFile = jpegFile;
                    } else
                        return;
                } else
                    return;
            }
            if (!previewImage.exists())
                ImageImporter.createScaledImage(previewImage, originalImage,
                        ImageImporter.PREVIEW_WIDTH,
                        ImageImporter.PREVIEW_HEIGHT);
            LOGGER.info("Creating thumbnail for " + photograph.getFileName()
                    + " at " + previewImage.getAbsolutePath());
            ModelLocator.getInstance().updatePreviewPath(
                    photograph.getPhotoId(), previewImage.getAbsolutePath());
            DBHelper.getInstance().updatePreviewPath(photograph.getPhotoId(),
                    previewImage.getAbsolutePath());
        } catch (Exception e) {
            LOGGER.error("error", e);
        } finally {
            ImageLibrary.getInstance().ow.unlock();
        }
    }

    public static boolean isRawFile(File file) {
        if (file.getName().toUpperCase().endsWith(".CR2")
                || file.getName().toUpperCase().endsWith(".NEF")) {
            return true;
        }
        
        return false;
    }

}
